<template>
<!--  <div>-->
    <el-autocomplete v-model="value"
                     class="top-search" popper-class="my-autocomplete"
                     :fetch-suggestions="querySearch"
                     :placeholder="$t('search')"
                     @select="handleSelect">
          <template v-slot:default="{ item }">
            <i :class="[item[iconKey],'icon']"></i>
            <div class="name">{{ item[labelKey] }}</div>
            <div class="addr">{{ item[pathKey] }}</div>
          </template>
    </el-autocomplete>
<!--  </div>-->
</template>

<script setup>
import {useUserStore} from "../../../store/modules/user.js";
import website from "@/config/website.js";
import {validatenull} from "utils/validate.js";
import { useRouter} from "vue-router"

defineOptions({
  name: 'top-search',
  inheritAttrs: false,
})

const optionData = reactive({
  value: "",
  menuList: []
})
const {value, menuList} = toRefs(optionData)

function created() {
  getMenuList();
}

created()

const labelKey = computed(() => {
  return website.menu.label
})
const pathKey = computed(() => {
  return website.menu.path
})
const iconKey = computed(() => {
  return website.menu.icon
})

const menu = computed(() => {
  const userStore = useUserStore();
  return userStore.menu
})
watch(menu, (val) => {
  getMenuList();
}, {
  flush: 'post'
})

function getMenuList() {
  const findMenu = list => {
    if (!list) {
      // watch的时候，可能还没拿到userStore.menu的数据
      return
    }
    for (let i = 0; i < list.length; i++) {
      const ele = Object.assign({}, list[i]);
      const childrenKey = website.menu.children;
      if (validatenull(ele[childrenKey])) {
        optionData.menuList.push(ele);
      } else {
        findMenu(ele[childrenKey]);
      }
    }
  };
  optionData.menuList = [];
  const userStore = useUserStore();
  findMenu(userStore.menu);
}

function querySearch(queryString, cb) {
  let restaurants = optionData.menuList;
  let results = queryString
      ? restaurants.filter(createFilter(queryString))
      : restaurants;
  // 调用 callback 返回建议列表的数据
  cb(results);
}

function createFilter(queryString) {
  return restaurant => {
    return (
        restaurant[labelKey.value]
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
    );
  };
}


const router = useRouter();

function handleSelect(item) {
  optionData.value = "";
  router.push({
    path: item[pathKey.value],
    query: item.query
  });
}
</script>

<style lang="scss">
.my-autocomplete {
  li {
    line-height: normal !important;
    padding: 7px !important;

    .icon {
      margin-right: 5px;
      display: inline-block;
      vertical-align: middle;
    }

    .name {
      display: inline-block;
      text-overflow: ellipsis;
      overflow: hidden;
      vertical-align: middle;
    }

    .addr {
      padding-top: 5px;
      width: 100%;
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
</style>